package com.yuanda.wordhot.web.admin;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.octo.captcha.service.CaptchaService;
import com.yuanda.wordhot.util.ContextUtil;
import com.yuanda.wordhot.web.validator.LoginValidator;
import com.yuanda.wordhot.web.validator.command.LoginCommand;

/**
 * 权限控制器
 */
@Controller
@RequestMapping("/admin")
public class SecurityController {
	
	private final static Logger logger = LoggerFactory.getLogger(SecurityController.class);

	private LoginValidator loginValidator = new LoginValidator();
	
	@Autowired
	private CaptchaService captchaService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String showLoginForm(Model model,
			@ModelAttribute LoginCommand command) {
		return "admin/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(Model model, @ModelAttribute LoginCommand command,HttpSession session,
			BindingResult errors) {
		//首先校验必填字段不为空
		loginValidator.validate(command, errors);

		if (errors.hasErrors()) {
			return showLoginForm(model, command);
		}
		//校验验证码是否正确
		doCaptchaValidate(command,session,errors);
		
		if (errors.hasErrors()) {
			return showLoginForm(model, command);
		}
		
		//然后登陆
		UsernamePasswordToken token = new UsernamePasswordToken(
				command.getEmail(), command.getPassword(),
				command.isRememberMe());
		try {
			SecurityUtils.getSubject().login(token);
		} catch (AuthenticationException e) {
			errors.rejectValue("password","error.password.error",
					"用户名或密码错误.  请重试.");
		}

		if (errors.hasErrors()) {
			return showLoginForm(model, command);
		} else {
			return "redirect:/admin/";
		}
	}



	@RequestMapping("/logout")
	public String logout() {
		SecurityUtils.getSubject().logout();
		ContextUtil.setCurrentUser(null);
		return "redirect:admin/login";
	}
	
	@RequestMapping(value="/jkRandom",method = RequestMethod.GET)
	public void jkRandom(HttpServletRequest request,HttpServletResponse response){
		response.setDateHeader("Expires", 1L);
		response.addHeader("Pragma", "no-cache");
		//Http 1.1 header
		response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
        response.setContentType("image/png");
        ServletOutputStream out = null;
        try {
            out=response.getOutputStream();
            String captchaId = request.getSession().getId();
            BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId, request.getLocale());
            //String writerNames[] = ImageIO.getWriterFormatNames();
            ImageIO.write(challenge, "png", out);
            out.flush();
        } catch (Exception e) {
        	logger.error("生成验证码出错",e);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                
            	
            	logger.error("生成验证码出错",e);
            }
        }
	}
    
	/**
	 * 校验验证码
	 * @param command
	 * @param session
	 * @param errors
	 */
	private void doCaptchaValidate(LoginCommand command, HttpSession session,
			BindingResult errors) {
        try {
            String captchaID = session.getId();
            String random = command.getRandom();
            if(!captchaService.validateResponseForID(captchaID, random)){
            	errors.rejectValue("random", "error.random.nomath", "验证码错误,请输入正确验证码");
            }
        } catch (Exception e) {
            	errors.rejectValue("random","error.random.error",
    					"生成验证码异常,请联系管理员");
        }
	}

}
